package com.tender.exceptions.exphandler;

import com.tender.common.Result;
import com.tender.constants.Constants;
import com.tender.enums.ErrorTypeEnum;
import com.tender.exceptions.CommonException;
import com.tender.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Object handleAllExceptions(Exception ex) {

        // 默认错误
        String msg = Constants.DEFAULT_ERROR_MSG;
        Result<String> result = Result.fail(msg);
        int code = HttpStatus.INTERNAL_SERVER_ERROR.value();

        if (ex instanceof IllegalArgumentException) {
            IllegalArgumentException exception = (IllegalArgumentException) ex;
            String errorCode = exception.getMessage();
            code = Integer.parseInt(errorCode);
            result.setCode(code);
            result.setMsg(ErrorTypeEnum.getMessage(code));
            return result;
        } else if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
            String errorCode = exception.getAllErrors().get(0).getDefaultMessage();
            if (StringUtils.isNotBlank(errorCode)) {
                code = Integer.parseInt(errorCode);
            }
            result.setCode(code);
            result.setMsg(ErrorTypeEnum.getMessage(code));
            return result;
        } else if(ex instanceof CommonException){
            CommonException exception = (CommonException) ex;
            result.setCode(exception.getCode());
            result.setMsg(exception.getMessage());
            return result;
        }

        result.setCode(code);
        result.setMsg(ErrorTypeEnum.getMessage(code));

        if (StringUtils.isBlank(result.getMsg())) {

            result.setMsg(msg);
            HttpServletRequest request = ServletUtils.getRequest();
            log.error(" ******* 请求 uri：{}, method：{}", request.getRequestURI(), request.getMethod());
            log.error(" ******* 全局异常处理器，具体异常：", ex);
        }

        return result;
    }

}
